<script>
	import {
		LOGINCONTROLLER,
		DICCONTROLLER,
		LINECONTROLLER,
		ORGCONTROLLER,
	} from "./api/sys";
	// #ifdef APP-PLUS
	var jpushModule = uni.requireNativePlugin("JG-JPush");
	// #endif
	export default {
		data() {
			return {
				jyJPush: "",
				socketStatus: "",
				userInfo: '',
				checkedValue: "",
			};
		},
		globalData: {
			overInfo: {}, //检修完成的数据
		},
		onShow() {
			// plus.runtime.setBadgeNumber(19);
		},
		onLaunch: function() {
			this.initSettingUrl();
			//  TO DO  应该用userID 来判断，同时 当用户退出登录的时候，默认要把用户名和密码填充
			if (uni.getStorageSync('userId')) {
				console.log('sssss-------------app页面---')
				uni.redirectTo({
					url: "/pages/index/index",
					success: () => {
						// #ifdef APP-PLUS
						plus.navigator.closeSplashscreen()
						// #endif
					}
				})
				if (!this.$store.state.alarmLevels.lenght && !this.$store.state.lineTree.lenght && !this.$store.state
					.reeByOrgnum.lenght && !this.$store.state.workProfession.lenght) {
					this.userInfo = JSON.parse(uni.getStorageSync("userInfo"));
					this.$store.state.userInfo = this.userInfo
					this.major = this.userInfo?.roles && this.userInfo?.roles[0].major
					this.getDicData()


				}
			} else {
				uni.reLaunch({
					url: '/pages/system/login/index',
					success: () => {
						// #ifdef APP-PLUS
						plus.navigator.closeSplashscreen()
						// #endif

					}
				})
			}

			this.initPosition();
			// this.newWebsocketInit()
			// #ifdef APP-PLUS
			if (uni.getSystemInfoSync().platform == "ios") {
				// 请求定位权限
				let locationServicesEnabled = jpushModule.locationServicesEnabled();
				let locationAuthorizationStatus =
					jpushModule.getLocationAuthorizationStatus();
				// console.log('locationAuthorizationStatus',locationAuthorizationStatus)
				if (locationServicesEnabled == true && locationAuthorizationStatus < 3) {
					jpushModule.requestLocationAuthorization((result) => {
						// console.log('定位权限',result.status)
					});
				}

				jpushModule.requestNotificationAuthorization((result) => {
					let status = result.status;
					if (status < 2) {
						uni.showToast({
							icon: "none",
							title: "您还没有打开通知权限",
							duration: 3000,
						});
					}
				});

				jpushModule.addGeofenceListener((result) => {
					let code = result.code;
					let type = result.type;
					let geofenceId = result.geofenceId;
					let userInfo = result.userInfo;
					uni.showToast({
						icon: "none",
						title: "触发地理围栏",
						duration: 3000,
					});
				});
			}

			// jpushModule.initJPushService();
			jpushModule.setLoggerEnable(true);
			jpushModule.addConnectEventListener((result) => {
				let connectEnable = result.connectEnable;
				uni.$emit("connectStatusChange", connectEnable);
			});

			//极光后台推送
			jpushModule.addNotificationListener((result) => {
				let notificationEventType = result.notificationEventType;
				let messageID = result.messageID;
				let title = result.title;
				let content = result.content;
				let extras = result.extras;
				console.log(result);
				uni.showToast({
					icon: "none",
					title: content,
					duration: 3000,
				});
				this.$store.commit("setMessage", content);
				this.$store.commit("setExtras", extras);
			});

			//极光后台自定义消息
			jpushModule.addCustomMessageListener((result) => {
				let type = result.type;
				let messageType = result.messageType;
				let content = result.content;
				console.log(result);
				uni.showToast({
					icon: "none",
					title: content,
					duration: 3000,
				});
			});
			// #endif

			// jpushModule.addLocalNotificationListener(result=>{
			// 	let messageID = result.messageID
			// 	let title = result.title
			// 	let content = result.content
			// 	let extras = result.extras
			// 	console.log(result);
			// 	uni.showToast({
			// 		icon: 'none',
			// 		title: JSON.stringify(result),
			// 		duration: 3000
			// 	})
			// })
			// console.log('App loaded')


		},
		methods: {
			checkedMajor() {
				let majorList = []
				if (this.major) {
					this.major.split(',').forEach((item, index) => {
						let filterItem = this.$store.state.workProfession.filter(filItem => {
							return filItem.code == item
						})
						if (filterItem.lenght > 0) {
							majorList[index] = {
								name: filterItem[0].value,
								code: item,
								value: filterItem[0].value
							}

							if (this.$store.state.userInfo.checkMajor) {
								this.checkedValue = this.$store.state.userInfo.checkMajor
							} else {
								this.checkedValue = majorList[0].code
							}
						}
					})
				}
				this.$store.state.majorOptions = majorList
				this.$store.commit('setUserInfo', {
					...this.$store.state.userInfo,
					checkMajor: this.checkedValue
				})
				uni.setStorageSync("userInfo", JSON.stringify(this.$store.state.userInfo));
			},
			async getDicData() {
				console.log('ssssssssss-----')
				// 获取报警等级
				const alarmLevels = await this.fetch(
					"post",
					this.$store.state.baseUrl + DICCONTROLLER.DICLISTSBYDICTYPE, {
						dicClass: "alarm_level" // 报警等级
					},
					false
				);
				this.$store.commit("setData", {
					alarmLevels: (alarmLevels?.data.map &&
						alarmLevels?.data.map((item) => ({
							code: item.code,
							value: item.value,
							props: (item.remark && typeof item.remark == "object" && JSON.parse(
								item.remark)) || {},
						}))) || [],
				});
				// 获取线路
				const lineList = await this.fetch(
					"get",
					this.$store.state.baseUrl + LINECONTROLLER.ALLLINES
				);
				this.$store.commit("setData", {
					lineTree: lineList.data,
				});
				// 获取机构
				const orglist = await this.fetch(
					"get",
					this.$store.state.baseUrl + ORGCONTROLLER.ALLORGS
				);
				// { orgnum: this.userInfo?.departid }
				if (orglist.success) {
					this.$store.commit("setData", {
						reeByOrgnum: orglist.data,
					});
				}
				// 获取工单类别
				const res = await this.fetch(
					"post",
					this.$store.state.baseUrl + DICCONTROLLER.DICLISTSBYDICTYPE, {
						dicClass: "workorder_type" // 工单类别
					},
					false
				);
				this.$store.commit("setData", {
					workOrderType: res?.data,
				});
				// 获取专业
				const res1 = await this.fetch(
					"post",
					this.$store.state.baseUrl + DICCONTROLLER.DICLISTSBYDICTYPE, {
						dicClass: "profession_type" // 专业分类
					},
					false
				);
				this.$store.commit("setData", {
					workProfession: res1?.data,
				});

				// 获取状态
				const res4 = await this.fetch(
					"post",
					this.$store.state.baseUrl + DICCONTROLLER.DICLISTSBYDICTYPE, {
						dicClass: "workorder_status" // 工单状态
					},
					false
				);
				this.$store.commit("setData", {
					workOrderState: res4?.data,
				});
				const res5 = await this.fetch(
					"post",
					this.$store.state.baseUrl + DICCONTROLLER.DICLISTSBYDICTYPE, {
						dicClass: "application_type" // 申请类别
					},
					false
				);
				this.$store.commit("setData", {
					applicationType: res5?.data,
				});

				const res6 = await this.fetch(
					"post",
					this.$store.state.baseUrl + DICCONTROLLER.DICLISTSBYDICTYPE, {
						dicClass: "job_type" // 作业类别
					},
					false
				);
				this.$store.commit("setData", {
					workType: res6?.data,
				});
				const res7 = await this.fetch(
					"post",
					this.$store.state.baseUrl + DICCONTROLLER.DICLISTSBYDICTYPE, {
						dicClass: "constr_area" // 施工区域
					},
					false
				);
				this.$store.commit("setData", {
					workArea: res7?.data,
				});
				const res8 = await this.fetch(
					"post",
					this.$store.state.baseUrl + DICCONTROLLER.DICLISTSBYDICTYPE, {
						dicClass: "故障现象"
					},
					false
				)
				this.$store.commit("setData", {
					fault: res8?.data,
				});

				this.checkedMajor()
			},
			newWebsocketInit() {
				clearTimeout(this.emergenceTaskID)
				this.emergenceTaskWebcoket = uni.connectSocket({
					url: this.$store.state.wsEmerUrl + '/socket/1/emergencyToApp',
					complete: () => {}
				})

				this.emergenceTaskWebcoket.onOpen(() => {
					clearTimeout(this.emergenceTaskID)
					console.log("WebSocket ---mergency--12--- 已连接!");
				})
				this.emergenceTaskWebcoket.onError((error) => {
					console.log("WebSocket ---mergency--12--- 出错了!", error);
					this.emergenceTaskID = setTimeout(() => {
						this.emergenceTaskWebcoket = null
						this.newWebsocketInit()
					}, 10000)
				})
				this.emergenceTaskWebcoket.onClose((error) => {
					// console.log("WebSocket ---mergency--12--- 关闭了!", error);
					// if (error.code !== 1000) {
					// 	this.emergenceTaskID = setTimeout(() => {
					// 		this.emergenceTaskWebcoket = null
					// 		this.newWebsocketInit()
					// 	}, 10000)
					// }
				})
				this.emergenceTaskWebcoket.onMessage((message) => {
					console.log("websocket推送过来的消息：", message.data)
					try {
						let emerToastInfo = JSON.parse(message.data);
						if (
							emerToastInfo.message.personIds &&
							emerToastInfo.message.personIds.search(this.getUserId()) != -1
						) {
							this.$store.commit('setwsEmerValue', !this.$store.state.wsEmerValue)
							// if (emerToastInfo.message.processCode == 1) {
							// 	uni.showToast({
							// 		title: "收到调度发布信息！",
							// 		icon: "none",
							// 	});
							// } else 
							if (emerToastInfo.message.processCode == 1) {
								// uni.showToast({
								// 	title: "收到指挥发布信息！",
								// 	icon: "none",
								// 	duration: 10000,
								// });
								uni.showModal({
									title: "应急信息",
									content: "收到指挥发布信息！",
									showCancel: false,

								})
							} else if (emerToastInfo.message.processCode == 4) {
								uni.showModal({
									title: "应急信息",
									content: "收到派单信息！",
									showCancel: false,
								})
								// uni.showToast({
								// 	title: "收到派单信息！",
								// 	icon: "none",
								// 	duration: 10000,
								// });
							}
						}
					} catch (e) {
						this.$store.commit('setEmerUpdataValue', '')
						setTimeout(() => {
							this.$store.commit('setEmerUpdataValue', message.data)
						})
						console.log("websocket推送过来的消息：error---", message)
						//TODO handle the exception
					}

				})
			},
			initSettingUrl() {
				let ip = uni.getStorageSync("ip");
				let port = uni.getStorageSync("port");

				if (ip && port) {
					this.$store.state.wsEmerUrl = "ws://" + ip + ":" + port;
					this.$store.state.baseEmerUrl = "http://" + ip + ":" + port;
					this.$store.state.baseProductUrl = "http://" + ip + ":" + port;
					this.$store.state.baseFaultUrl = "http://" + ip + ":" + port;
					this.$store.state.baseUrl = "http://" + ip + ":" + port;
					this.$store.state.baseOrderUrl = "http://" + ip + ":" + port;
					this.$store.state.wsOrderUrl = "ws://" + ip + ":" + port;
				}

				// 报警模块的url
				// uni.setStorageSync('baseUrl', 'http://115.29.234.80:8295');
			},
			initPosition() {
				uni.getLocation({
					type: "gcj02",
					geocode: true, //获取城市具体地址
					success: (res) => {
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
					},
					fail: function(res) {
						// console.error(res);
					},
				});
			},
		},
	};
</script>

<style>
	/*每个页面公共css */
	view,
	text {
		box-sizing: border-box;
	}

	text {
		display: inline-block;
	}

	.u-cell,
	.u-field {
		padding-left: 0 !important;
	}

	.u-cell__value {
		color: #3e3a39 !important;
	}

	.u-list-item {
		margin: 0 !important;
		width: 80px !important;
		height: 80px !important;
	}

	.status .van-cell__value,
	.status .u-cell__value {
		color: #71c76f !important;
	}

	.u-progress {
		display: none !important;
	}

	.u-border-top:after {
		border-top: 0px !important;
	}

	.u-field__input-wrap {
		text-align: right !important;
	}

	.u-label,
	.fild-body {
		flex: auto !important;
	}

	.uni-input-input {
		background-color: transparent !important;
	}

	.uni-checkbox-input {
		width: 16px !important;
		height: 16px !important;
		margin-right: 10px !important;
	}
</style>
<style>
	/* @import 'vant/lib/index.css'; */
	@import "./static/css/common/common.css";
	@import "./static/css/common/style.css";
</style>

<style lang="scss">
	/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
	@import "uview-ui/index.scss";
</style>